﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using Razre.Base;
using System.Windows;
using System.Windows.Data;

namespace Razre
{
    /// <summary>
    /// Class to provide factory creation of a ViewModel
    /// </summary>
    public static class ViewModelFactory
    {
        /// <summary>
        /// Method to create a ViewModel with an associate View
        /// </summary>
        /// <typeparam name="T">Type of ViewModel to create</typeparam>
        /// <returns>The created ViewModel with associated View</returns>
        public static T CreateViewModel<T>()
            where T : BaseViewModel, new()
        {
            try
            {
                //create a new instance of the view model
                T viewModel = new T();

                //try to find a datatemplate to this viewmodel by its own type
                DataTemplateKey key = new DataTemplateKey(typeof(T));
                DataTemplate template = Application.Current.FindResource(key) as DataTemplate;

                //ensure a template was found
                if (template != null)
                {
                    //create an instance of a ContentControl and set its ContentTemplate to the found DataTemplate
                    ContentControl view = new ContentControl();
                    view.ContentTemplate = template;

                    //set the content of the ContenControl to the ViewModel
                    view.Content = viewModel;

                    //store the created View inside the ViewModel
                    viewModel.View = view;

                    return viewModel;
                }
                else
                {
                    throw new Exception("Template Not Found, please ensure the DataTemplate is able to be found by Application Resources either manually or through the ThemeManager");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("An Exception occurred while creating a ViewModel, please see the inner exception for the details", ex);
            }
        }
    }
}
